<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="添加商品信息"
                type="info"
                center
                show-icon
                :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex-0"
                finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单 -->
      <el-form :model="goodsForm"
               :rules="goodsRules"
               ref="goodsFormRef"
               label-width="100px"
               label-position="top">
        <!-- 标签页 -->
        <el-tabs tab-position="left"
                 v-model="activeIndex"
                 :before-leave="tabLeave"
                 @tab-click="tabClick">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息"
                       name="0">
            <el-form-item label="商品名称"
                          prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格(元)"
                          prop="goods_price">
              <el-input v-model="goodsForm.goods_price"
                        type="number"
                        min="0"></el-input>
            </el-form-item>
            <el-form-item label="商品重量(千克)"
                          prop="goods_weight">
              <el-input v-model="goodsForm.goods_weight"
                        type="number"
                        min="0"></el-input>
            </el-form-item>
            <el-form-item label="商品数量"
                          prop="goods_number">
              <el-input v-model="goodsForm.goods_number"
                        type="number"
                        min="0"
                        value="0"></el-input>
            </el-form-item>
            <!-- 商品分类的级联选择器 -->
            <el-cascader v-model="goodsForm.goods_cat"
                         :options="cataList"
                         :props="cataPorps"
                         @change="handleChange">

            </el-cascader>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数"
                       name="1">
            <el-form-item :label="item.attr_name"
                          v-for="(item,i) in goodsManyCataList"
                          :key="i">

              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item2,i2) in item.attr_vals"
                             :key="i2"
                             :label="item2"></el-checkbox>

              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性"
                       name="2">
            <el-form-item :label="item.attr_name"
                          v-for="(item,i) in goodsOnlyCataList"
                          :key="i">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片"
                       name="3">

            <el-upload class="upload-demo"
                       :action="actionURL"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       :on-success="handleSuccess"
                       list-type="picture"
                       :headers="headersObj">
              <el-button size="small"
                         type="primary">点击上传</el-button>
              <div slot="tip"
                   class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容"
                       name="4">
            <quill-editor v-model="goodsForm.goods_introduce" />
            <el-button type="primary"
                       class="btnadd"
                       @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="提示"
               :visible.sync="dialogVisible"
               width="50%">
      <img :src="previewPath"
           class="show-img">
    </el-dialog>

  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data () {
    return {
      // 完成进度
      activeIndex: '0',
      // 表单数据
      goodsForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 表单验证规则
      goodsRules: {
        goods_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { min: 1, max: 5, message: '请输入正确价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量', trigger: 'blur' },
          { min: 1, max: 5, message: '请输入正确重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品数量', trigger: 'blur' },
          { min: 1, max: 6, message: '请输入0-999999的数字', trigger: 'blur' }
        ]

      },
      // 商品分类列表
      cataList: [],
      // 选中商品分类
      cataPorps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 商品动态参数列表
      goodsManyCataList: [],
      // 商品静态参数列表
      goodsOnlyCataList: [],
      // 多选框选中的值
      checked: [],
      actionURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewPath: '',
      // 图片预览显示隐藏
      dialogVisible: false

    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.cataList = res.data
    },
    // 监听商品分类变动
    handleChange () {
      if (this.goodsForm.goods_cat.length !== 3) {
        this.goodsForm.goods_cat = []
      }
    },
    // tab栏变动事件
    tabLeave (newName, oldName) {
      if (this.goodsForm.goods_cat.length !== 3) {
        this.$message.info('请选择正确的商品分类')
        return false
      }
    },
    // tab切换事件
    async tabClick () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.goodsForm.goods_cat[this.goodsForm.goods_cat.length - 1]}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.goodsManyCataList = res.data

        console.log(this.goodsManyCataList)
      }
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.goodsForm.goods_cat[this.goodsForm.goods_cat.length - 1]}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
        this.goodsOnlyCataList = res.data
      }
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview (file) {
      this.dialogVisible = true
      this.previewPath = file.response.data.url
    },
    // 文件列表移除文件时的钩子
    handleRemove (file) {
      const filePath = file.response.data.tem_path
      const i = this.goodsForm.pics.findIndex(x => x.pic === filePath)
      this.goodsForm.pics.splice(i, 1)
    },
    // 文件列表成功上传文件时的钩子
    handleSuccess (response) {
      const picInfo = { pic: response.data.tmp_path }
      this.goodsForm.pics.push(picInfo)
    },
    // 添加商品
    async add () {
      this.$refs.goodsFormRef.validate(vaild => {
        if (!vaild) {
          return this.$message.error('请填写必要的表单项!')
        }
      })

      const form = _.cloneDeep(this.goodsForm)

      form.goods_cat = form.goods_cat.join(',')

      // 处理动态信息
      this.goodsManyCataList.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(' ')
        }

        this.goodsForm.attrs.push(newInfo)
      })
      // 处理静态信息
      this.goodsOnlyCataList.forEach(item => {
        console.log(item.attr_vals)
        const newInfo = {
          attr_id: item.attr_id,

          attr_value: item.attr_vals
        }

        this.goodsForm.attrs.push(newInfo)
      })
      form.attrs = this.goodsForm.attrs

      const { data: res } = await this.$http.post('goods', form)
      if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
      this.$message.success('添加商品成功！')
      this.$router.push('/goods')
    }
  },
  created () {
    this.getCateList()
  }

}
</script>
<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}
.show-img {
  width: 100%;
}
.btnadd {
  margin-top: 20px;
}
</style>
